'''
    天气API
'''

import json
from django.http import JsonResponse
from django.views import View
from utils.response import CommonResponseMixin
from thirdparty import juhe
from urllib.parse import quote
from utils.auth import already_authorized
from utils.response import ReturnCode
from authorization.models import User


# 天气函数视图
def weather(request):
    if request.method == 'GET':
        city = request.GET.get('city')
        data = juhe.weather(city)

        return JsonResponse(data=data, status=200)

    elif request.method == 'POST':
        received_body = request.body
        received_body = json.loads(received_body)
        cities = received_body.get('cities')
        response_data = []

        for city in cities:
            cityname = city.get('city')
            result = juhe.weather(cityname)
            result['city'] = city
            response_data.append(result) # 往数组中添加一项

        # 这里需要将 sale 改为false，因为返回的是一个数组
        return JsonResponse(data=response_data, safe=False, status=200)


# 天气类视图
# 继承 Django 的 View 类
# 继承自己写的通用返回类 CommonResponseMixin
class WeatherView(View, CommonResponseMixin):
    def get(self, request):
        # 判断是否有登录
        if not already_authorized(request):
            print('这个用户未登录')
            response = self.wrap_json_response(data={}, code=ReturnCode.UNAUTHORIZED)
            return JsonResponse(data=response, self=False)
        else:
            print('这个用户已登录')
            data = []
            open_id = request.session.get('open_id')
            user = User.objects.filter(open_id=open_id)[0]
            cities = json.loads(user.focus_cities)
            for city in cities:
                result = juhe.weather(city.get('city'))
                result['city_info'] = city
                data.append(result)
            response = self.wrap_json_response(data=data, code=ReturnCode.SUCCESS)
        return JsonResponse(data=response, safe=False)

    def post(self, request):
        data = []
        received_body = request.body.decode('utf-8')
        received_body = json.loads(received_body)
        cities = received_body.get('cities')
        for city in cities:
            cityname = quote( city.get('city') )
            result = juhe.weather(cityname)
            result['city'] = city
            data.append(result) # 往数组中添加一项

        data = self.wrap_json_response(data=data)
        return JsonResponse(data=data, safe=False)
